package com.ali.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * NIO多路复用
 */
public class NIOSelectorMain {
    public static void main(String[] args) {
        try {
            //构建监听服务
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //设置监听服务为非阻塞状态
            serverSocketChannel.configureBlocking(false);
            //绑定监听端口
            serverSocketChannel.bind(new InetSocketAddress(8080));
            //构建多路复用器
            Selector selector = Selector.open();
            //在多路复用器中注册客户端连接事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {
                //多路复用器阻塞，等待事件发生
                selector.select();
                handle(selector);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理多路复用器事件
     */
    private static void handle(Selector selector) {
        try {
            //构建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1);
            int length;

            //获取多路复用器的所有事件
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                //判断是否是客户端连接事件
                if (selectionKey.isAcceptable()) {
                    //获取监听服务
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                    //获取客户端连接
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    //设置客户端连接为非阻塞状态
                    socketChannel.configureBlocking(false);
                    //在多路复用器中注册数据传输事件
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println("接收客户端连接");
                }
                //判断是否是数据传输事件
                else if (selectionKey.isReadable()) {
                    //获取客户端连接
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    StringBuilder stringBuffer = new StringBuilder();
                    while (true) {
                        //写入内容至缓冲区
                        length = socketChannel.read(byteBuffer);
                        if (length > 0) {
                            stringBuffer.append(new String(byteBuffer.array(), 0, length));
                            //清理缓冲区
                            byteBuffer.clear();
                        } else if (length == 0) {
                            break;
                        } else if (length == -1) {
                            System.out.println("客户端断开连接");
                            //取消注册
                            selectionKey.cancel();
                            break;
                        }
                    }
                    System.out.println("接收内容：" + stringBuffer);
                }
                //移除事件
                iterator.remove();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
